package com.jsyxdl.k3cloud.utils;

import cn.hutool.extra.spring.SpringUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.AES;
import com.hustcad.plm.pdm.user.service.ErpBomService;
import com.jsyxdl.k3cloud.listener.K3CloudHttpService;
import com.jsyxdl.service.ErpK3cloudService;
import com.ty.basic.exception.message.SystemErrorCodeEnum;
import com.ty.pdm.system.workFlow.listener.common.BOMVerificationLineListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

public class SendErpDataUtils {
    public static String acctID;
    public static String username;
    public static String password;
    private static final Logger log = LoggerFactory.getLogger(SendErpDataUtils.class);

    public SendErpDataUtils() {
        init();
    }

    public static void init() {
        ErpBomService erpBomService=SpringUtil.getBean(ErpBomService.class);
        Map<String,Object> map=new HashMap<>();
        map.put("title","金蝶云星空配置");
        List<Map<String,Object>> list=erpBomService.selectFiguration(map);
        if(list.size()>0){
            acctID= (String) list.get(0).get("acctid");
            username= (String) list.get(0).get("username");
            password=  AES.decrypt((String) list.get(0).get("password"), "huazPlm@15999899");
        }
        log.info("SendErpDataUtils.init() >>>>>>>selectFiguration " + list.toString());
    }

    /**
     * 用于已有输出数据直接发送给ERP
     * @param executionType
     * @param outMap
     * @param outMap
     * @return
     * @throws Exception
     */
    public static JSONObject sendErpDataTaskWorkder(Map<String, Object> executionType, Map<String,Object> outMap)throws Exception{
        init();
        K3CloudHttpService k3CloudHttpService= SpringUtil.getBean(K3CloudHttpService.class);

        int execution= (int) executionType.get("execution_type");
        String uri= (String) executionType.get("uri");
        String method= (String) executionType.get("method");
        String protocol= (String) executionType.get("protocol");
        String port= (String) executionType.get("port");
        String home= (String) executionType.get("home");
        String formid= (String) executionType.get("formid");
        if(execution==1){
            JSONObject httpResult = new JSONObject();
            httpResult.put("IsSuccessByAPI",true);

            if(k3CloudHttpService.getCookieStr()==null){
                Map<String,Object> login=new HashMap<>();
                login.put("acctID",acctID);
                login.put("lcid",2052);
                login.put("username",username);
                login.put("password",password);
                login.put("isKickOff",true);


                if("http".equals(protocol)){
                    httpResult = k3CloudHttpService.postServiceHttpToJSONObject(HttpMethodEnum.HTTP, home+":"+port+"/K3Cloud/Kingdee.BOS.WebApi.ServicesStub.AuthService.ValidateUser.common.kdsvc", login);
                }
            }

            if(httpResult.containsKey("IsSuccessByAPI")){
                if(httpResult.getBoolean("IsSuccessByAPI")){
                    if("post".equals(method)){
                        Map<String,Object> outParameter=new HashMap<>();
                        outParameter.put("formid",formid);
                        outParameter.put("data",outMap);
                        httpResult = k3CloudHttpService.postServiceHttpToJSONObject(HttpMethodEnum.HTTP,home+":"+port+uri,outParameter);
                        JSONObject resultObj=httpResult.getJSONObject("Result");
                        JSONObject responseStatus=resultObj.getJSONObject("ResponseStatus");
                        if(responseStatus.getBooleanValue("IsSuccess")==false){
                            if(responseStatus.getLongValue("MsgCode")==1){
                                k3CloudHttpService.setCookieStr(null);
                                k3CloudHttpService.setKdserviceSessionid(null);

                                if("http".equals(protocol)){
                                    Map<String,Object> login=new HashMap<>();
                                    login.put("acctID",acctID);
                                    login.put("lcid",2052);
                                    login.put("username",username);
                                    login.put("password",password);

                                    httpResult = k3CloudHttpService.postServiceHttpToJSONObject(HttpMethodEnum.HTTP,home+":"+port+"/K3Cloud/Kingdee.BOS.WebApi.ServicesStub.AuthService.ValidateUser.common.kdsvc",login);
                                }

                                if(httpResult.containsKey("IsSuccess")){
                                    if(httpResult.getBoolean("IsSuccess")==true){
                                        httpResult = k3CloudHttpService.postServiceHttpToJSONObject(HttpMethodEnum.HTTP,home+":"+port+uri,outParameter);
                                    }
                                    else{
                                        return httpResult;
                                    }
                                }
                                else if(httpResult.containsKey("IsSuccessByAPI")){
                                    if(httpResult.getBoolean("IsSuccessByAPI")==true){
                                        httpResult = k3CloudHttpService.postServiceHttpToJSONObject(HttpMethodEnum.HTTP,home+":"+port+uri,outParameter);
                                    }
                                    else{
                                        return httpResult;
                                    }
                                }
                            }
                        }
                        log.info("ERP结果："+httpResult.toJSONString());

                        return k3CloudHttpService.erpResultDispose(httpResult,executionType,outMap);
                    }
                    return httpResult;
                }
                else{
                    throw SystemErrorCodeEnum.WORK_FLOW_CONTENT_ERROR.getException("不能登录ERP");
                }
            }
            else{
                throw SystemErrorCodeEnum.WORK_FLOW_CONTENT_ERROR.getException("不能登录ERP");
            }
        }

        return null;
    }

    public static  JSONObject plmToK3CloudTaskWorkderByParameter(String code, String k3cloud, JSONObject parameter)throws Exception{
        K3CloudHttpService k3CloudHttpService= SpringUtil.getBean(K3CloudHttpService.class);
        init();

        Map<String,Object> outMap=null;
        try {
            outMap=plmSelectK3CloudOutByParameter(code,k3cloud,parameter);

            Map<String, Object> executionType=k3CloudHttpService.getExecutionType(code,k3cloud);
            if(executionType==null){
                k3CloudHttpService.saveLogs("","","接口参数错误","",JSONObject.toJSONString(outMap),k3cloud,code);
                throw SystemErrorCodeEnum.WORK_FLOW_CONTENT_ERROR.getException("接口参数错误");

            }
            int execution= (int) executionType.get("execution_type");
            String uri= (String) executionType.get("uri");
            String method= (String) executionType.get("method");
            String protocol= (String) executionType.get("protocol");
            String port= (String) executionType.get("port");
            String home= (String) executionType.get("home");
            String formid= (String) executionType.get("formid");

            if(execution==1){
                JSONObject httpResult = new JSONObject();
                httpResult.put("IsSuccessByAPI",true);

                if(k3CloudHttpService.getCookieStr()==null){
                    Map<String,Object> login=new HashMap<>();
                    login.put("acctID",acctID);
                    login.put("lcid",2052);
                    login.put("username",username);
                    login.put("password",password);
                    if("http".equals(protocol)){
                        httpResult = k3CloudHttpService.postServiceHttpToJSONObject(HttpMethodEnum.HTTP,home+":"+port+"/K3Cloud/Kingdee.BOS.WebApi.ServicesStub.AuthService.ValidateUser.common.kdsvc",login);
                    }
                }

                if(httpResult.getBoolean("IsSuccessByAPI")){
                    if("post".equals(method)){
                        Map<String,Object> outParameter=new HashMap<>();
                        outParameter.put("formid",formid);
                        outParameter.put("data",JSONObject.toJSONString(outMap));
                        httpResult = k3CloudHttpService.postServiceHttpToJSONObject(HttpMethodEnum.HTTP,home+":"+port+uri,outParameter);
                        JSONObject resultObj=httpResult.getJSONObject("Result");
                        JSONObject responseStatus=resultObj.getJSONObject("ResponseStatus");
                        if(responseStatus.getBooleanValue("IsSuccess")==false){
                            if(responseStatus.getLongValue("MsgCode")==1){
                                k3CloudHttpService.setCookieStr(null);
                                k3CloudHttpService.setKdserviceSessionid(null);

                                if("http".equals(protocol)){
                                    Map<String,Object> login=new HashMap<>();
                                    login.put("acctID",acctID);
                                    login.put("lcid",2052);
                                    login.put("username",username);
                                    login.put("password",password);
                                    httpResult = k3CloudHttpService.postServiceHttpToJSONObject(HttpMethodEnum.HTTP,home+":"+port+"/K3Cloud/Kingdee.BOS.WebApi.ServicesStub.AuthService.ValidateUser.common.kdsvc",login);
                                }

                                if(httpResult.containsKey("IsSuccess")){
                                    if(httpResult.getBoolean("IsSuccess")){
                                        httpResult = k3CloudHttpService.postServiceHttpToJSONObject(HttpMethodEnum.HTTP,home+":"+port+uri,outParameter);
                                    }
                                    else{
                                        k3CloudHttpService.saveLogs("","","不能登录ERP0",httpResult.toJSONString(),JSONObject.toJSONString(outMap),k3cloud,code);
                                        return httpResult;
                                    }
                                }
                                else if(httpResult.containsKey("IsSuccessByAPI")){
                                    if(httpResult.getBoolean("IsSuccessByAPI")){
                                        httpResult = k3CloudHttpService.postServiceHttpToJSONObject(HttpMethodEnum.HTTP,home+":"+port+uri,outParameter);
                                    }
                                    else{
                                        k3CloudHttpService.saveLogs("","","不能登录ERP1",httpResult.toJSONString(),JSONObject.toJSONString(outMap),k3cloud,code);
                                        return httpResult;
                                    }
                                }
                            }
                        }

                    }
                    JSONObject resultObj=httpResult.getJSONObject("Result");
                    JSONObject responseStatus=resultObj.getJSONObject("ResponseStatus");
                    if(responseStatus.getBooleanValue("IsSuccess")) {
                        k3CloudHttpService.saveLogs("","","成功",httpResult.toJSONString(),JSONObject.toJSONString(outMap),k3cloud,code);
                    }
                    return httpResult;
                }
                else{
                    k3CloudHttpService.saveLogs("","","不能登录ERP2",httpResult.toJSONString(),JSONObject.toJSONString(outMap),k3cloud,code);
                    throw SystemErrorCodeEnum.WORK_FLOW_CONTENT_ERROR.getException("不能登录ERP");

                }
            }
        }
        catch (Exception e){
            k3CloudHttpService.saveLogs("","",e.getMessage(),"",JSONObject.toJSONString(outMap),k3cloud,code);
            throw SystemErrorCodeEnum.WORK_FLOW_CONTENT_ERROR.getException(e.getMessage());
        }
        finally {
        }

        return null;
    }

    public static Map<String,Object> plmSelectK3CloudOutByParameter(String code, String k3cloud, JSONObject parameter)throws Exception{
        K3CloudHttpService k3CloudHttpService= SpringUtil.getBean(K3CloudHttpService.class);
        try {
            PlmPartOptionUtils plmPartOptionUtils= SpringUtil.getBean(PlmPartOptionUtils.class);
            if(plmPartOptionUtils==null) throw new Exception("查询组件异常");

            List<Map<String, Object>> options=k3CloudHttpService.getOptions(code, k3cloud);

            Map<String,Object> inMap=k3CloudHttpService.getInTreeMap(code,k3cloud);

            Map<String,Object> parameters=new HashMap<>();
            Map<String,Object> bomKeyValue=new HashMap<>();
            Map<String,Object> partKeyValue=new HashMap<>();
            for(Map<String,Object> option: options){
                if("表单属性".equals(option.get("plmtype"))){
                    k3CloudHttpService.setInTree((List<Map<String, Object>>) inMap.get(option.get("plm_source_type_id")),parameter,partKeyValue);
                    break;
                }
            }
            bomKeyValue.putAll(partKeyValue);
            return k3CloudHttpService.plmToK3CloudOut(code,k3cloud,parameters,bomKeyValue);
        }
        finally {
        }
    }
}
